import { t } from 'i18next'
import { fetchGetPlatformServiceUrl } from '@/api/global'
import Alert from '@/components/Alert'
import { getUrlParams } from '@/utils'
import { useEffect } from 'react'

let __alert = false

function initStorageEvent() {
	let moid = getUrlParams()
	if (!moid) {
		var _arr = window.location.pathname.split('/')
		moid = _arr[_arr.length - 1] || ''
	}
	let meeting_machine_link: any = localStorage.getItem('meeting_machine_link')
	if (!meeting_machine_link) return
	try {
		meeting_machine_link = JSON.parse(meeting_machine_link)
		if (meeting_machine_link.meeting_machine_moid !== meeting_machine_link.list[moid]) {
			if (__alert) return
			__alert = true
			Alert(t('当前页面环境发生变化，请重新进入会场管理'), () => {
				fetchGetPlatformServiceUrl()
					.then((data) => {
						window.location.href = data + '/index.html'
					})
					.catch((err) => {
						window.location.href = '/meeting/index.html'
					})
			})
		}
	} catch (e) {
		console.error(t('获取会议、机房关系报错'), e)
	}
}
export default function useStorageEvent() {
	useEffect(() => {
		window.addEventListener('storage', initStorageEvent)
		return () => {
			window.removeEventListener('storage', initStorageEvent)
		}
	}, [])
	return null
}
